import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
  selector: 'ege-buffer',
  templateUrl: './buffer.component.html',
  styleUrls: ['./buffer.component.scss']
})
export class BufferComponent implements OnInit {

  private _buffer: number = 0;
  private _unit: string = 'kilometers';

  @Input()
  set buffer(value: number) { 
    this._buffer = value;
    this.setControlValue('buffer', value);
  }

  get buffer(): number {
    return this._buffer;
  }

  @Input()
  set unit(value: string) {
    this._unit = value;
    this.setControlValue('unit', value);
  }

  get unit(): string {
    return this._unit;
  }

  @Output() onOk: EventEmitter<any> = new EventEmitter();
  @Output() onCancel: EventEmitter<any> = new EventEmitter();

  formGroup: FormGroup;

  constructor() { }

  ngOnInit() {
    this.formGroup = this.formBuilder();
  }

  formBuilder(): FormGroup {
    const formGroup: FormGroup = new FormGroup({
      unit: new FormControl(this.unit),
      value: new FormControl(this.buffer),
      clone: new FormControl(false)
    });
    return formGroup;
  }

  setControlValue(controlName: string, value: any): void {
    if(this.formGroup) {
      const control = this.formGroup.controls[controlName];
      if(control) {
        control.setValue(value);
      }
    }
  }

  onClickConfirm(): void {
    for (const i in this.formGroup.controls) {
      this.formGroup.controls[ i ].markAsDirty();
    }
    this.onOk.emit(this.formGroup.value);
    setTimeout(() => this.setControlValue('value', this.buffer), 400);
  }

  onClickCancel(): void {
    const values = {
      unit: this.unit,
      value: this.buffer,
      clone: false
    };
    this.onCancel.emit();
    this.formGroup.reset(values);
  }

}
